import { App, Button, DatePicker, Flex, Form, Input, Modal, Select, Space, Table, Tag } from "antd";
import { useContext, useEffect, useState } from "react";
import user_api, { USER_ROLE } from "../api/users";
import { useForm } from "antd/es/form/Form";
import Search from "antd/es/input/Search";
import dayjs from "dayjs";
import { provider_api } from "../api/providers";
import { Global } from "../main";

export function Provider() {
    const [searchLoading, setSearchLoading] = useState(false)
    const [providerPage, setProviderPage] = useState({ total: 0, content: [] })
    const [providerReq, setProviderReq] = useState({ keyword: '', page: 1, size: 15 })
    const [updateProviderModalOpen, setUpdateProviderModalOpen] = useState(false)
    const [createProviderModalOpen, setCreateProviderModalOpen] = useState(false)
    const [createProviderForm] = useForm();
    const [updateProviderForm] = useForm();
    const { message, modal } = App.useApp();
    const [currentProvider, setCurrentProvider] = useState(null);
    const { role } = useContext(Global)
    const columns = [
        {
            title: '供应商名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '联系人',
            dataIndex: 'contact_name',
            key: 'contact_name',
        },
        {
            title: '联系方式',
            dataIndex: 'contact_phone',
            key: 'contact_phone',
        },
        {
            title: '备注',
            dataIndex: 'remarks',
            key: 'remarks',
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 150,
            render: (_, row) => (<Space size={'middle'}>
                <Button type="link" onClick={() => {
                    updateProviderForm.setFieldsValue({ ...row, deadline_time: dayjs(row.deadline_time, 'YYYY-MM-DD') });
                    console.log(row)
                    setCurrentProvider(row);
                    setUpdateProviderModalOpen(true)
                }} disabled={role === USER_ROLE.READONLY}>编辑</Button>
                <Button type="link" danger onClick={() => modal.confirm({
                    title: "删除供应商",
                    content: `确认要删除供应商：${row.name}吗？删除供应商将删除对应供应商下所有数据！`,
                    onOk: () => {
                        provider_api.deleteProvider(row.id).then(() => {
                            reFreshProject();
                        }).catch(e => message.error(e))
                    },
                    okText: '确定',
                    cancelText: '取消'
                })} disabled={role === USER_ROLE.READONLY}>删除</Button>
            </Space>)
        },
    ];
    const reFreshProject = (ur) => {
        let request = providerReq;
        if (!!ur) {
            request = ur;
        }
        provider_api.pageProvider(request).then(data => {
            setProviderPage({ ...data, content: data.content.map(it => ({ ...it, key: it.id })) })
            setSearchLoading(false)
        }).catch(e => message.error(e))
    }

    useEffect(() => {
        reFreshProject()
    }, []);

    return <>
        <Space style={{ margin: '10px' }}>
            <Search size="large" placeholder="输入关键字进行搜素" style={{ maxWidth: '30vw' }} loading={searchLoading} onSearch={(value) => {
                setSearchLoading(true)
                setProviderReq({ ...providerReq, keyword: value })
                reFreshProject({ ...providerReq, keyword: value })
            }}></Search>
            <Button size="large" type="primary" onClick={() => {
                setCurrentProvider(null)
                createProviderForm.setFieldsValue(null)
                createProviderForm.resetFields()
                setCreateProviderModalOpen(true)
            }} disabled={role === USER_ROLE.READONLY}>创建</Button>
        </Space>
        <Table size="small" pagination={{
            position: ["bottomLeft"],
            pageSizeOptions: [providerReq.size],
            total: providerPage.total,
            current: providerReq.page,
            pageSize: providerReq.size,
            onChange: (page, pageSize) => {
                setProviderReq({ ...providerReq, page: page, size: pageSize });
                reFreshProject({ ...providerReq, page: page, size: pageSize })

            }
        }} dataSource={providerPage.content} columns={columns}></Table>
        <Modal maskClosable={false} title="编辑供应商" okText="确定" cancelText="取消" onOk={() => {
            updateProviderForm.validateFields().then(data => {
                provider_api.updateProvider(data).then(() => {
                    reFreshProject();
                    setUpdateProviderModalOpen(false)
                }).catch(e => message.error(e.response.data || "系统异常"))
            });

        }} onCancel={() => setUpdateProviderModalOpen(false)} open={updateProviderModalOpen}>
            <Form labelCol={{ span: 6 }} value={currentProvider} wrapperCol={{ span: 18 }} form={updateProviderForm} initialValues={currentProvider}>
                <Form.Item label="索引" name={"id"} hidden>
                    <Input />
                </Form.Item>
                <Form.Item label="供应商名称" name={"name"} rules={[{
                    required: true,
                    message: '请输入供应商名称'
                }]}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="联系人" name={"contact_name"}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="联系方式" name={"contact_phone"}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="备注" name={"remarks"} rules={[{max: 50}]}>
                    <Input.TextArea></Input.TextArea>
                </Form.Item>
            </Form>
        </Modal>
        <Modal maskClosable={false} title="新建供应商" okText="确定" cancelText="取消" onOk={() => {
            createProviderForm.validateFields().then(data => {
                provider_api.createProvider(data).then(() => {
                    reFreshProject();
                    setCreateProviderModalOpen(false)
                }).catch(e => message.error(e.response.data || "系统异常"))
            });

        }} onCancel={() => setCreateProviderModalOpen(false)} open={createProviderModalOpen}>
            <Form labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} form={createProviderForm} initialValues={currentProvider}>
                <Form.Item label="供应商名称" name={"name"} rules={[{
                    required: true,
                    message: '请输入供应商名称'
                }]}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="联系人" name={"contact_name"} rules={[{
                    required: true,
                    message: '请输入联系人'
                }]}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="联系方式" name={"contact_phone"} rules={[{
                    required: true,
                    message: '请输入联系方式'
                }]}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="备注" name={"remarks"} rules={[{max: 50}]}>
                    <Input.TextArea></Input.TextArea>
                </Form.Item>
            </Form>
        </Modal>
    </>
}